Skip to content

Fix type narrowing with not isinstance(x, cls) in classmethods#21312

Open
sanyamk23 wants to merge 3 commits intopython:masterfrom
sanyamk23:fix-issue-21271
Open

Fix type narrowing with not isinstance(x, cls) in classmethods#21312
sanyamk23 wants to merge 3 commits intopython:masterfrom
sanyamk23:fix-issue-21271

Conversation

@sanyamk23
Copy link
Copy Markdown

Adjust get_type_range_of_type to set is_upper_bound=False for Self types, allowing precise narrowing in negative checks. Fixes #21271.

Description

This PR addresses an issue where not isinstance(x, cls) inside a @classmethod failed to correctly narrow the type of x when it involved Self.

In mypy/checker.py, get_type_range_of_type was conservatively setting is_upper_bound=True for all TypeType objects (like cls: Type[Self]). This prevented the narrowing logic from removing Self from a union in the else branch, as it assumed the check wasn't precise.

This change sets is_upper_bound=False specifically for Self types (and also handles NoneType and final classes similarly). This allows mypy to correctly narrow x to the remaining types in the union when the isinstance(x, cls) check fails.

Checklist

  • Read the Contributing Guidelines
  • Add tests for all changed behaviour.
  • Make sure CI passes (Regression tests ran locally).

sanyam-brudite and others added 3 commits April 24, 2026 18:29
Adjust get_type_range_of_type to set is_upper_bound=False for Self types, allowing precise narrowing in negative checks. Fixes python#21271.
@github-actions
Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

comtypes (https://github.com/enthought/comtypes)
+ comtypes/_post_coinit/unknwn.py:347: error: Unused "type: ignore" comment  [unused-ignore]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

not isinstance(x, cls) inside classmethod does not narrow type

2 participants